<template>
  <div class="container">
    <div class="button-group">
      <el-button class="margin-lr-md" type="primary" size="small" @click="qwBluetooth.connect()">
        {{ isConnect ? '切换智能笔' : '连接智能笔' }}
      </el-button>
      <el-button v-if="isConnect" type="primary" size="small" @click="bluetooth.disconnect()">断开连接</el-button>
      <el-button v-if="isConnect" type="primary" size="small" @click="dropdownHandleClick('start')">开始获取离线</el-button>
      <el-button v-if="isConnect" type="primary" size="small" @click="dropdownHandleClick('delete')">清除离线数据</el-button>
      <el-button v-if="isConnect" @click="exportData" class="el-button" size="small" type="primary">导出数据</el-button>
    </div>

    <div v-if="isConnect" class="canvas-container">
        <tql-canvas ref="canvas" id="canvas" :width="width / 2" :height="height / 2" :lineWidth="lineWidth" :lineColor="lineColor"></tql-canvas>
    </div>
  </div>
</template>

<script>
import ota from '../tqlsdk/otaUpgrade';
import FormatDate from '../utils/FormatDate';
import PenDataBar from '../components/pc/PenDataBar.vue';
import { mapGetters, mapActions, mapMutations } from 'vuex';
import TqlCanvas from '../components/tql/tql-canvas.vue';
import * as MethodName from '../tqlsdk/MethodName';
import * as DataName from '../utils/dataName';
export default {
  components: { TqlCanvas, PenDataBar },
  data() {
    return {
      progress: 0,
      lineWidth: 1,
      lineColor: "#000000",
      predefineColors: ['#000000', '#ABABAB', '#FF0000', '#FFA500', '#0000FF', '#008000', '#D600D9'],
    }
  },
  computed: {
    ...mapGetters(['width', 'height', 'penDataList', 'isConnect', 'bluetooth','qwBluetooth']),
  },
  methods: {
    ...mapMutations(['setIsConnect', 'restorePenDataList']),
    ...mapActions(['setPenDataList', 'connectListener', 'disconnectListener', 'penDataListener', 'batchSendCommand']),
    dropdownHandleClick(command) {
      switch (command) {
        case 'start':
          this.qwBluetooth.startOfflineTransfer()
          break;
        case 'pause':
          this.qwBluetooth.pauseOfflineTransfer()
          break;
        case 'continue':
          this.qwBluetooth.continueOfflineTransfer()
          break;
        case 'stop':
          this.qwBluetooth.stopOfflineTransfer()
          break;
        case 'delete':
          this.$dialog.confirm({
                  title: '提示',
                  message: '确定清除离线数据吗？',
              })
              .then(() => {
                  this.qwBluetooth.deleteOfflineData()
              })
              .catch(() => {
                  return
              });
          break;
          // this.qwBluetooth.deleteOfflineData()
          // break;
      }
    },

    //连接时 触发
    connect(data) {
      data ? this.batchSendCommand() : this.$message.error('连接失败')
    },

    //断开连接时 触发
    disconnect(data) {
      //重置数据
      this.restorePenDataList()
      //清屏
      this.$refs.canvas.clearAllData()
    },
    //处理笔数据
    handlePenData(data) {
      console.log("处理笔数据："+data);
      switch (data.operation) {
        case MethodName.A8: //获取电量 //isCharging
          this.setPenDataList({
            label: DataName.ElectricQuantity,
            value: data.electricQuantity
          })
          break;
        case MethodName.AA: //获取RTC
          this.setPenDataList({
            label: DataName.RealTimeClock,
            value: FormatDate(data.timestamp)
          })
          break;
        case MethodName.AC: //设置RTC
          if (data.isSuccess) this.bluetooth.getRealTimeClock()
          this.$message.success(`校正RTC${data.isSuccess ? '成功' : '失败'}`)
          break;
        case MethodName.B0: //获取自动关机时间
          this.setPenDataList({
            label: DataName.AutoShutdownTime,
            value: `${data.time}${data.unit}`
          })
          break;
        case MethodName.B2: //设置自动关机时间
          if (data.isSuccess) this.bluetooth.getAutoShutdownTime()
          this.$message.success(`设置自动关机时间${data.isSuccess ? '成功' : '失败'}`)
          break;
        case MethodName.B4: //恢复出厂设置
          this.$message.success(`恢复出厂设置${data.isSuccess ? '成功' : '失败'}`)
          break;
        case MethodName.B6: //获取Flash占比
          this.setPenDataList({
            label: DataName.FlashProportion,
            value: data.proportion
          })
          break;
        case MethodName.B8: //获取是否压力唤醒
          this.setPenDataList({
            label: DataName.PressureRouse,
            value: data.isOpen
          })
          break;
        case MethodName.BA: //设置是否压力唤醒
          if (data.isSuccess) this.bluetooth.getPressureRouse()
          this.$message.success(`设置笔尖压力唤醒${data.isSuccess ? '成功' : '失败'}`)
          break;
        case MethodName.BC: //获取蜂鸣器是否开启
          this.setPenDataList({
            label: DataName.Buzzer,
            value: data.isOpen
          })
          break;
        case MethodName.BE: //设置蜂鸣器是否开启
          if (data.isSuccess) this.bluetooth.getBuzzerIsOpen()
          this.$message.success(`设置蜂鸣器${data.isSuccess ? '成功' : '失败'}`)
          break;
        case MethodName.D0: //获取压力敏感度
          this.setPenDataList({
            label: DataName.PressureSensor,
            value: data.sensor
          })
          break;
        case MethodName.D2: //设置压力敏感度
          if (data.isSuccess) this.bluetooth.getPressureSensor()
          this.$message.success(`设置压力敏感度${data.isSuccess ? '成功' : '失败'}`)
          break;
        case MethodName.D8: //获取压力校正值
          this.setPenDataList({
            label: DataName.PressureCorrection,
            value: `${data.pressure_20}-${data.pressure_300}`
          })
          break;
        case MethodName.DA: //获取MCU版本
          this.setPenDataList({
            label: DataName.MCUFirmwareVersion,
            value: data.version
          })
          break;
        case MethodName.DC: //获取客户Id
          console.log(data);
          break;
        case MethodName.DE: //设置客户Id
          if (data.isSuccess) this.bluetooth.getCustomerId()
          this.$message.success(`设置客户Id${data.isSuccess ? '成功' : '失败'}`)
          break;
        case MethodName.E4: //获取笔的类型
          this.setPenDataList({
            label: DataName.PenType,
            value: data.type
          })
          break;
        case MethodName.C0: //获取离线数据量
          this.setPenDataList({
            label: DataName.OfflineDataSize,
            value: `${data.size}${data.unit}`
          })
          break;
        case MethodName.C2_0: //开始离线数据传输
          this.$message.success(`开始获取离线数据${data.isSuccess ? '成功' : '失败'}`)
          break;
        case MethodName.C2_1: //停止离线数据传输
          this.$message.success(`停止获取离线数据${data.isSuccess ? '成功' : '失败'}`)
          break;
        case MethodName.CB_0: //暂停离线数据传输
          this.$message.success(`暂停获取离线数据${data.isSuccess ? '成功' : '失败'}`)
          break;
        case MethodName.CB_1: //继续离线数据传输
          this.$message.success(`继续获取离线数据${data.isSuccess ? '成功' : '失败'}`)
          break;
        case MethodName.C5: //离线数据传输结束
          this.$message.success('离线数据获取完成')
          break;
        case MethodName.C8: //删除离线数据
          this.$message.success(`删除离线数据${data.isSuccess ? '成功' : '失败'}`)
          break;
        case MethodName.A0: //获取蓝牙设备名 - 笔名
          this.setPenDataList({
            label: DataName.BluetoothName,
            value: data.name
          })
          break;
        case MethodName.A2: //设置蓝牙设备名 - 笔名
          if (data.isSuccess) this.bluetooth.getBluetoothName()
          this.$message.success(`设置笔名${data.isSuccess ? '成功' : '失败'}`)
          break;
        case MethodName.A4: //获取蓝牙MAC -笔MAC
          this.setPenDataList({
            label: DataName.BluetoothMAC,
            value: data.mac
          })
          break;
        case MethodName.A6: //获取蓝牙固件版本
          this.setPenDataList({
            label: DataName.BluetoothFirmwareVersion,
            value: data.version
          })
          break;

        //add by ridong
          case MethodName.DL: //获取离线数据量
          this.$message.success(`获取数据量为：${data.dataLength}`)
          this.$refs.canvas.dataLength = data.dataLength
          break;
          case MethodName.COD: //清空缓存数据
          console.log("清空数据的返回值："+data.isSuccess)
          this.$message.success(`清空缓存数据${data.isSuccess ? '成功' : '失败'}`)
          break;
      }
    },
    onChange(file) {
      ota.upgrade(file.raw, (progress) => {
        this.progress = progress
      }).then(() => {
        this.$message.success('升级成功')
        this.$refs.upload.clearFiles()
      }).catch(() => {
        this.$message.error('升级失败')
      })
    },
    async upgrade() {
      const device = await ota.connect().catch((err) => {
        console.dir(err)
        switch (err.message) {
          case "Bluetooth adapter not available.":
            this.$message.warning('蓝牙适配器不可用')
            break;
          case "User cancelled the requestDevice() chooser.":
            this.$message.warning('取消连接')
            break;
          default:
            this.$message.error(device)
            break;
        }
      })
        this.$message.success(device)
    },
    /**
     * @name 导出数据为文本格式
     */
    exportData() {
      // 获取当前页的笔迹数据
      const canvas = this.$refs.canvas;
      const currentPageData = canvas._data.pageIdList;

      if (!currentPageData || currentPageData.length === 0) {
        alert('当前页无数据，无法导出！');
        return;
      }

      // 将数据转换为字符串格式，并去除方括号和逗号
      const dataString = currentPageData.join('\n');

      // 创建Blob对象并触发下载
      const blob = new Blob([dataString], { type: 'text/plain;charset=utf-8' });
      const url = URL.createObjectURL(blob);
      const link = document.createElement('a');
      link.href = url;
      link.download = `pen_data_page.txt`;
      link.click();

      // 释放URL对象
      URL.revokeObjectURL(url);
    }
  },
  async created() {
    this.connectListener(this.connect)
    this.disconnectListener(this.disconnect)
    this.penDataListener(this.handlePenData)
    if (!navigator.bluetooth) {
      this.$notify.error({
        title: '提示',
        message: '该浏览器不支持蓝牙',
        duration: 0,
      });
      return
    }
    const isAvailability = await navigator.bluetooth.getAvailability()
    if (!isAvailability) {
      this.$notify.error({
        title: '提示',
        message: '未检测到蓝牙适配器',
        duration: 0,
      });
      return
    }
  }
}
</script>

<style lang="less" scoped>
.pen-info
{
  margin-left: .25rem;
  width: 2.8rem;
  height: 8.44rem;
}

/deep/ .el-button
{
  padding: .09rem .15rem;
}

.slider-width
{
  min-width: 2rem;
}

.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 1rem;
}

.button-group {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  margin-bottom: 1rem;
}

.canvas-container {
  width: 100%;
  display: flex;
  justify-content: center;
}
</style>